package com.simpledemo.activity;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.simpledemo.R;

public class HandlerActivity extends AppCompatActivity {

    private TextView text;
    private Handler workHandler;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            text.setText(msg.what + "秒就要双十一啦!");
        }
    };
    interface HandleBack{
       void sendMessageToWorkThread(Handler handle);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        initView();
       // doLogic1();
        doLogic2();

    }

    private void doLogic2() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                handler.sendMessage(msg);
            }
        }).start();


        for (int i = 0; i < 100; i++) {
            final int finalI = i;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    text.setText(finalI + "秒就要双十一啦!");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

        }
    }

    private void doLogic1() {
        sendToWorkThread(new HandleBack() {
            @Override
            public void sendMessageToWorkThread(Handler handle) {
                for (int i = 0; i < 100; i++) {
                    Message msg = Message.obtain();
                    msg.what = i;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void sendToWorkThread(final HandleBack back) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                workHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Toast.makeText(HandlerActivity.this,msg.what + "秒就要双十一啦!",Toast.LENGTH_LONG).show();
                    }
                };
                back.sendMessageToWorkThread(workHandler);
                Looper.loop();
            }
        }).start();
    }

    private void initView() {
        text = findViewById(R.id.text);
    }
}
